<template>
  <div class="folder-processor">
    <el-card class="processor-card">
      <template #header>
        <div class="card-header">
          <h3>处理视频文件夹</h3>
        </div>
      </template>

      <div class="processor-form">
        <div class="form-item">
          <div class="form-label">视频文件夹路径：</div>
          <el-input v-model="folderPath" placeholder="请输入视频文件夹路径，例如：E:\视频\抖音" clearable :disabled="loading">
            <template #prepend>
              <el-icon>
                <folder />
              </el-icon>
            </template>
          </el-input>
          <div class="form-tip">填写服务器可访问的视频文件夹路径</div>
        </div>

        <div class="form-actions">
          <el-button type="primary" @click="processFolder" :loading="loading"
            :disabled="!folderPath || loading">
            开始处理
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Folder } from '@element-plus/icons-vue';
import copywritingService from '@/services/copywritingService';
import settingsService from '@/services/settingsService';

export default defineComponent({
  name: 'FolderProcessor',
  components: {
    Folder
  },
  emits: ['process-complete'], // 确保emit定义包含这个事件
  setup(props, { emit }) {
    const folderPath = ref('');
    const loading = ref(false);

    const processFolder = async () => {
      if (!folderPath.value) {
        ElMessage.warning('请输入视频文件夹路径');
        return;
      }
      const apiKey = settingsService.getGlobal('apiKey');
      if (!apiKey) {
        ElMessage.warning('请前往系统设置页面， 配置OpenAI API Key');
        return;
      }

      loading.value = true;
      try {
        const result = await copywritingService.processFolder(folderPath.value, apiKey);

        if (result.success) {
          ElMessage.success(`处理完成，共提取 ${result.results ? result.results.length : 0} 个视频文件`);
          // 传递结果和API Key给父组件
          emit('process-complete', result.results, apiKey);
        } else {
          throw new Error(result.message || '处理失败');
        }
      } catch (error) {
        ElMessage.error(`处理文件夹失败: ${error.message}`);
      } finally {
        loading.value = false;
      }
    };

    return {
      folderPath,
      loading,
      processFolder
    };
  }
});
</script>

<style scoped>
.folder-processor {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.processor-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-item {
  margin-bottom: 15px;
}

.form-label {
  margin-bottom: 8px;
  font-weight: 500;
  color: #606266;
}

.form-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

.form-actions {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>